package com.ruoyi.utils;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.FileOutputStream;
import java.io.IOException;

public class HtmlToWord {



    public static void convertHtmlToDocx(String htmlContent, String outputPath) {
        Document doc = Jsoup.parse("<html><body>" + htmlContent + "</body></html>");
        XWPFDocument document = new XWPFDocument();

        boolean isFirstTitleProcessed = false; // 标记是否已经处理了第一个标题

        for (Element element : doc.body().children()) {
            if (!isFirstTitleProcessed && element.tagName().equalsIgnoreCase("h1")) {
                createStyledHeader(element.text(), document, true);
                isFirstTitleProcessed = true;
            } else if (element.tagName().equalsIgnoreCase("p")) {
                processParagraph(element, document);
            }
        }

        try (FileOutputStream out = new FileOutputStream(outputPath)) {
            document.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void processParagraph(Element element, XWPFDocument document) {
        String text = element.text();
        if (text.startsWith("一、") || text.startsWith("二、") || text.startsWith("三、")) { // 一级标题判断
            createStyledHeader(text, document, false);
        } else {
            XWPFParagraph paragraph = document.createParagraph();
            paragraph.setIndentationFirstLine(480); // 设置段落首行缩进
            XWPFRun run = paragraph.createRun();
            run.setFontFamily("仿宋_GB2312");
            run.setFontSize(16); // 三号字大小
            run.setText(text.replaceAll(" ", "\u00A0")); // 替换所有空格为不间断空格
        }
    }

    private static void createStyledHeader(String text, XWPFDocument document, boolean isMainTitle) {
        XWPFParagraph paragraph = document.createParagraph();
        if (isMainTitle) {
            paragraph.setAlignment(ParagraphAlignment.CENTER); // 文档标题居中
        }
        XWPFRun run = paragraph.createRun();
        if (isMainTitle) {
            run.setFontFamily("华文中宋");
            run.setFontSize(22); // 二号字大小
            run.setBold(true);
        } else {
            run.setFontFamily("仿宋_GB2312");
            run.setFontSize(16); // 三号字大小
            run.setBold(true);
        }
        run.setText(text);
    }
}